﻿using Business;
using Business.Attributes;
using Business.Auth;
using Business.Result;
using Business.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using static Args;

[Command(Group = "HTTP")]
[JsonArg2(Group = "HTTP")]
[Logger]
[Info("API")]
public partial class BusinessMember : BusinessBase
{
    public BusinessMember()
    {
        this.Logger = x =>
        {
            try
            {
                x.Value = x.Value?.ToValue();

                var log = x.JsonSerialize();

                Help.WriteLocal(log, console: true, write: x.Type == LoggerType.Exception);
            }
            catch (Exception exception)
            {
                Help.ExceptionWrite(exception, true, true);
            }
        };
    }

    /// <summary>
    /// 接口注释test001
    /// </summary>
    /// <param name="t"></param>
    /// <param name="c"></param>
    /// <param name="arg"></param>
    /// <returns>让返对象</returns>
    [Command(Group = "HTTP2")]
    public virtual async Task<dynamic> Test001(Token t, BusinessController c, [Attr2]Arg<Test001> arg)
    {
        //return c.Redirect("https://www.github.com");

        arg.Out.B = $"{arg.Out.B} {System.Guid.NewGuid().ToString("N")}";

        return this.ResultCreate(arg.Out);
    }

    public virtual async Task<dynamic> Test002(Token t, BusinessController c, Arg<Test001> arg)
    {
        arg.Out.A = $"{arg.Out.A} {System.Guid.NewGuid().ToString("N")}";

        return this.ResultCreate(arg.Out);
    }
}

public class JsonArg2Attribute : ArgumentAttribute
{
    public JsonArg2Attribute(int state = -12, string message = null, bool canNull = false) : base(state, message, canNull) { }

    public Newtonsoft.Json.JsonSerializerSettings Settings { get; set; }

    public override async Task<IResult> Proces(dynamic value)
    {
        var result = CheckNull(this, value);
        if (!result.HasData) { return result; }

        try
        {
            return this.ResultCreate(Newtonsoft.Json.JsonConvert.DeserializeObject(value, this.Meta.MemberType, Settings));
        }
        catch { return this.ResultCreate(State, Message ?? $"Arguments {this.Nick} Json deserialize error"); }
    }
}

public class Attr2 : ArgumentAttribute
{
    public Attr2(int state = -13, string message = null, bool canNull = false) : base(state, message, canNull) { }

    public override async Task<IResult> Proces(dynamic value)
    {
        Test001 value2 = value;
        value2.A = $"{value.A} 1234";

        return this.ResultCreate(value2);
    }
}

public class Args
{

    public class Test001
    {
        /// <summary>
        /// 用户名
        /// </summary>
        [CheckNull]
        [Size(Max = 11)]
        [Nick("参数 Test001.A")]
        public string A;

        public string B { get; set; }
    }
}